package hkr.vfu.bluecenter.backend;

import android.bluetooth.BluetoothSocket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by mattiasbowallius on 09/12/13.
 */
public class BluetoothSingleton {

    public static final String END = "END";
    public static final String OK = "OK";
    public static final String STOP = "\r";
    public static final String ERROR = "ERR";
    private static BluetoothSingleton instance;
    private Map<String, BluetoothSocket> sockets = new HashMap<String, BluetoothSocket>(7);

    public static BluetoothSingleton getInstance() {
        if (instance == null) {
            instance = new BluetoothSingleton();
        }
        return instance;
    }

    public boolean addSocket(String macAddress, BluetoothSocket socket) {
        if (!sockets.containsKey(macAddress) && sockets.size() < 8) {
            sockets.put(macAddress, socket);
            return true;
        }
        return false;
    }

    public void stopSocket(String macAddress) {
        try {
            if (sockets.containsKey(macAddress)) {
                BluetoothSocket socket = sockets.get(macAddress);
                socket.close();
                sockets.remove(macAddress);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void executeCommand(String macAddress, String command) {
        if (sockets.containsKey(macAddress)) {
        try {
            BufferedWriter outputStream = new BufferedWriter(new PrintWriter(sockets.get(macAddress).getOutputStream()));
            outputStream.write(command);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        }
    }

    public String readAnswerWithEnding(String macAddress, String ending) {
        char[] line = new char[1];
        StringBuilder output = new StringBuilder();
        try {
            BufferedReader inputStream = new BufferedReader(new InputStreamReader(sockets.get(macAddress).getInputStream()));
            while (true) {
                inputStream.read(line);
                output.append(line[0]);
                if (output.toString().endsWith(ending)) {
                    break;
                } else if (output.toString().endsWith(ERROR)) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return output.toString();
    }

    public boolean isConnected(String macAddress) {
        return sockets.containsKey(macAddress);
    }
}